import md5 from './md5.js';

import config from '../config.js'
var util = {};
let _app = null;

util.init = function (app){
	_app = app
}


util.requesthost = config.requesthost
util.imgHost = config.imgHost
util.ws = "ws://39.106.94.26:8282"
util.salt = "Uo3VHk3FQryHZSL"

util.md5 = function (str) {
	return md5(str)
};


//签名函数
function mySign(datas) {
  // datas.timestamp = num_to_time(Date.parse(new Date()) / 1000, false);
  var a = Array(), bb = {}; for (var i in datas) { a.push(i); } a.sort(); for (var i in a) { bb[a[i]] = datas[a[i]]; };
  
  var signs = [];
  for (var i in bb) {//将重新排序后的json取出存进signs
    signs.push(i + datas[i] + '');
  }
  
  var signstr_umd5 = signs.join('') + util.salt;
  var sign = util.md5(signstr_umd5);//所有参数的键值md5加密作为签名
  // console.log('加密后:' + JSON.stringify(sign));
  datas.sign = sign;
  // console.log(datas)
  return datas;
}



util.friendlyDate = function(timestamp) {
	var formats = {
		'year': '%n% 年前',
		'month': '%n% 月前',
		'day': '%n% 天前',
		'hour': '%n% 小时前',
		'minute': '%n% 分钟前',
		'second': '%n% 秒前',
	};

	var now = Date.now();
	var seconds = Math.floor((now - timestamp) / 1000);
	var minutes = Math.floor(seconds / 60);
	var hours = Math.floor(minutes / 60);
	var days = Math.floor(hours / 24);
	var months = Math.floor(days / 30);
	var years = Math.floor(months / 12);

	var diffType = '';
	var diffValue = 0;
	if (years > 0) {
		diffType = 'year';
		diffValue = years;
	} else {
		if (months > 0) {
			diffType = 'month';
			diffValue = months;
		} else {
			if (days > 0) {
				diffType = 'day';
				diffValue = days;
			} else {
				if (hours > 0) {
					diffType = 'hour';
					diffValue = hours;
				} else {
					if (minutes > 0) {
						diffType = 'minute';
						diffValue = minutes;
					} else {
						diffType = 'second';
						diffValue = seconds === 0 ? (seconds = 1) : seconds;
					}
				}
			}
		}
	}
	return formats[diffType].replace('%n%', diffValue);
}




util.formCheck = (condition=[],postdata)=>{
					
		// console.log(condition)
		var msgs = {
			req:'必填',
			num:'必须填数字',
			str:'必须填字符',
			phone:'手机号码格式不对',
			idcard:'身份证号格式有误'
		}
		
		var result = false
		
		for(var item in postdata){
			// console.log(item)
			for(var conditionitem in condition){
				
				// console.log(conditionitem)
				if( item == condition[conditionitem]['name'] ){
					console.log(item+'----------')
					let conditions = condition[conditionitem]['rule'].split('|')
					for(var index in conditions){
						switch (conditions[index]){
							case 'req':
									if(postdata[item]==''||null){
										console.log(item+msgs['req'])
										return condition[conditionitem]['textname']+msgs['req']
									}
								break;
							case 'num':
									if(postdata[item]==''){
										break;
									}
									// postdata[item] = postdata[item].replace(/\s*/g,"") - 0;
									var regular = /^\d+(\.\d+)?$/;
									if(regular.test(postdata[item])){//这是用正则表达是检查
										console.log('是数字')
									}else{
										console.log(item+msgs['num'])
										console.log(postdata[item])
										return condition[conditionitem]['textname']+msgs['num']
									}
								break;
							case 'str':
									if (typeof postdata[item] == 'string'){
										
									}else{
										console.log(item+msgs['str'])
										return condition[conditionitem]['textname']+msgs['str']
									}
								break;
							case 'phone':
									if(postdata[item]==''){
										break;
									}
									var regular = /^1(3|4|5|6|7|8|9)\d{9}$/;
									if(regular.test(postdata[item])){//这是用正则表达是检查
										console.log('手机号合规')
									}else{
										console.log(item+msgs['phone'])
										return condition[conditionitem]['textname']+msgs['phone']
									}
								break;
							case 'idcard':
									if(postdata[item]==''){
										break;
									}
									var regular =/^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/
									
									if(regular.test(postdata[item])){//这是用正则表达是检查
										console.log('身份证号合规')
									}else{
										console.log(item+msgs['idcard'])
										return condition[conditionitem]['textname']+msgs['idcard']
									}
								break;
							default:
								break;
						}
					}
					
					
				}
			}
			
			
		}
		
		return false;
	}







util.formatLocation = function(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

// 判断是否为数字
util.isNumber = function(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if(regPos.test(val) || regNeg.test(val)) {
        return true;
        } else {
        return false;
        }
}
 
// 请求封装
util.csAjax = function(url,data={},callback,isSilent){
	try {
		const value = uni.getStorageSync('userinfo');
		if (value) {
			// console.log(value);
			data['token'] = value['token']
		}
	} catch (e) {
		// error
		console.warn("未获取到本地登录记录")
	}
	
	if(isSilent){
		uni.showLoading({
			title:isSilent
		})
		
	}
	
	
	uni.request({
		url:util.requesthost+url,
		data:mySign(data),
		method:'POST',
		header: {
		  "Content-Type": "application/x-www-form-urlencoded",
		},
		complete: function(res){
			// console.log(res)
			// console.log(mySign(data))
			if(isSilent){
				uni.hideLoading();
				
			}
			
			// 特殊情况 401需要登录（未登录 登录过期等） 403接口无权限
			
			let codeArr = [
				401,
			]
			
			if(res.data.code == '403'){
				//新用户需要跳转至统一登录页面
				_app.$api.msg(res.data.msg)
			}
			
			if(res.data.code == 'u110'){
				//新用户需要跳转至统一登录页面
				_app.$fire.fire('newuser',{})
				// uni.redirectTo({
				// 	url:'/pages/index/index'
				// })
			}
			
			//需要登录
			if(codeArr.indexOf(res.data.code) != -1){
				util.login('weixin')
			}
			
			
		},
		success:function (res) {
			// 请求成功但结果异常 toast提示 
			if(!res.data.code==1){
				uni.showToast({
					duration:3000,
					icon:"none",
					title:res.data.msg
				})
			}
			
			
			//请求成功且结果正常执行回调
			if(res.data.code==1){
				callback(res.data)
			}
			
			
			
		},
		fail:function(err){
			// console.log(err)
			uni.showToast({
				icon:"none",
				title:"请求失败！"
			})
		}
		
	})
}


util.upload = function(filepath,callback,isSilent){
	if(isSilent){
		uni.showLoading({
			title:isSilent
		})
	}
	var data = {}
	
	try {
		const value = uni.getStorageSync('userinfo');
		if (value) {
			// console.log(value);
			data['token'] = value['token']
		}
	} catch (e) {
		// error
		console.warn("未获取到本地登录记录")
	}
	
	uni.uploadFile({
		url:util.requesthost+'/index/ajax/upload', //上传接口地址 根据不同项目实际填写
		filePath: filepath,
		name: 'file',
		formData: data,
		success: (uploadFileRes) => {
			callback(uploadFileRes.data)
			// console.log(uploadFileRes.data);
		},
		fail:(err)=>{
			console.log(err)
			uni.showToast({
				icon:'none',
				title:"上传失败",
				duration:2500
			})
		},
		complete:(res)=>{
			if(isSilent){
				uni.hideLoading();
			}
		}
	})
	
}


util.login = function (login_type='weixin'){
	
	// var login_type = 'weixin'
	uni.getProvider({
		service: 'oauth',
		success: function (res) {
			console.log(res.provider) 
			if (~res.provider.indexOf(login_type)) {
				uni.login({
					provider: login_type,
					success: function (loginRes) {
						// console.log(JSON.stringify(loginRes));
						
						var data  ={
							code:loginRes.code,
							
						}
						// console.log(JSON.stringify(e))
						util.csAjax('/addons/open/wxapp.user/codeLogin',data,(ret)=>{
							console.log(ret.data.userInfo)
							if(ret.data.userInfo){
								uni.setStorageSync('userinfo',ret.data.userInfo)
								_app.$fire.fire('logged',{data:ret.data});
								_app.$api.msg('自动登录成功')
							}
							
						},'Logging')
					}
				});
			}else{
				uni.showToast({
					title:"暂未开放，敬请期待！"
				})
			}
		}
	});
}


util.checkLogin = function(){
	var userinfo = uni.getStorageSync('userinfo');
	if(userinfo){
		return true
	}
	util.login()
	return false;
}

util.dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	},//时间戳转动态时间段
	time2str:function(num) {
		var now_num = Date.parse(new Date())/1000; 
		var ss = now_num - num;
	//	console.log(ss);
		while (ss<=60){
	//		一分钟内
			return '刚刚';
		}
		while (ss<=3600){
			
	//		一小时内
			var ff = ~~(ss/60);
			return ff+'分钟前';
		}
		while (ss<=86400){
	//		24小时内
			var hh = ~~(ss/3600);  
			return	hh+"小时前";
		}
		while (ss<=259200){
	//		3天内
			var dd = ~~(ss/86400);
			return dd+'天前';
		}
		
		while (ss>259200){
			var   now = new Date(num*1000);
			var   year=now.getFullYear();     
			var   month=now.getMonth()+1;   
			if(month<10){
				month = '0'+month;
			}
			var   day=now.getDate();   
			if(day<10){
				day = '0'+day;
			}
			var   hour=now.getHours();    
			if(hour<10){
				hour = '0'+hour;
			}
			var   minute=now.getMinutes();
			if(minute<10){
				minute = '0'+minute;
			}
			var   second=now.getSeconds();  
			if(second<10){
				second = '0'+second;
			}
			return   year+"-"+month+"-"+day
			// +" "+hour+":"+minute;
			//+":"+second  秒
		}
	},
	
};

//图片路径修复
util.imgUrlfix =function (urlstr){
	var reg = /^(http|https):\/\/.+$/;
	if(!reg.test(urlstr)){
		console.log("修复图片地址"+util.requesthost+urlstr)
		return util.requesthost+urlstr
	}else{
		return urlstr
	}
}

// 格式化图片样式
util.formatImg=function(html){
	var newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
		console.log(match)
		var match = match.replace(/class=\"\"/gi, '');
		var match = match.replace(/<img/gi, '<img class="img-responsive"');
		var match = match.replace(/style=\"(.*)\"/gi, ' ');
		console.log(match)
		return match;
	});
	return newContent;
}

// 时间戳格式化时间
util.formatTime = function(number,format) {  
  
  var formateArr  = ['Y','M','D','h','m','s'];  
  var returnArr   = [];  
  
  var date = new Date(number);  
  returnArr.push(date.getFullYear());  
  returnArr.push(formatNumber(date.getMonth() + 1));  
  returnArr.push(formatNumber(date.getDate()));  
  
  returnArr.push(formatNumber(date.getHours()));  
  returnArr.push(formatNumber(date.getMinutes()));  
  returnArr.push(formatNumber(date.getSeconds()));  
  
  for (var i in returnArr)  
  {  
    format = format.replace(formateArr[i], returnArr[i]);  
  }  
  return format;  
} 

//数据转化  
function formatNumber(n) {  
  n = n.toString()  
  return n[1] ? n : '0' + n  
} 


util.csdate = function(number){
	var weeks = ['日','一','二','三','四','五','六']
	var timestamp = number
	if(!timestamp){
		timestamp = new Date().getTime()
	}
	var date = new Date(timestamp);
	var data = {}
	
	data.date = date.getFullYear()+formatNumber(date.getMonth() + 1)+formatNumber(date.getDate())
	date.year = date.getFullYear()
	data.month = formatNumber(date.getMonth() + 1)
	data.day = formatNumber(date.getDate())
	data.re = date.getFullYear()+'-'+formatNumber(date.getMonth() + 1)+'-'+formatNumber(date.getDate())
	data.dateTime = timestamp
	data.week = weeks[date.getDay()];
	 
	return data;
}




module.exports = util;

